/**
 * 更新防具装备base值的脚本
 * 功能：根据防具数据更新equipment_base表中对应防具的base值
 */

const mysql = require('mysql2/promise');

// 数据库连接配置
const dbConfig = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    charset: 'utf8mb4'
};

// 防具数据映射 (type=3)
const armorData = {
    // base=1: 甲类防具（力）
    1: [
        { id: 82, name: "藤甲·力", lvl: 1, price: 1500 },
        { id: 83, name: "青铜甲·力", lvl: 2, price: 3000 },
        { id: 84, name: "镔铁甲·力", lvl: 3, price: 6000 },
        { id: 85, name: "精钢甲·力", lvl: 4, price: 12000 },
        { id: 86, name: "乌金甲·力", lvl: 5, price: 24000 },
        { id: 87, name: "混元甲·力", lvl: 6, price: 48000 },
        { id: 88, name: "地煞甲·力", lvl: 7, price: 96000 },
        { id: 89, name: "天罡甲·力", lvl: 8, price: 192000 },
        { id: 90, name: "亮银甲·力", lvl: 9, price: 384000 },
        { id: 91, name: "紫金甲·力", lvl: 10, price: 768000 }
    ],
    // base=2: 衣类防具（血）
    2: [
        { id: 92, name: "单衣·血", lvl: 1, price: 1500 },
        { id: 93, name: "短衣·血", lvl: 2, price: 3000 },
        { id: 94, name: "长袍·血", lvl: 3, price: 6000 },
        { id: 95, name: "道袍·血", lvl: 4, price: 12000 },
        { id: 96, name: "礼服·血", lvl: 5, price: 24000 },
        { id: 97, name: "蚕服·血", lvl: 6, price: 48000 },
        { id: 98, name: "庙服·血", lvl: 7, price: 96000 },
        { id: 99, name: "朝服·血", lvl: 8, price: 192000 },
        { id: 100, name: "长冠服·血", lvl: 9, price: 384000 },
        { id: 101, name: "冕冠服·血", lvl: 10, price: 768000 }
    ],
    // base=3: 衣类防具（精）
    3: [
        { id: 102, name: "单衣·精", lvl: 1, price: 1500 },
        { id: 103, name: "短衣·精", lvl: 2, price: 3000 },
        { id: 104, name: "长袍·精", lvl: 3, price: 6000 },
        { id: 105, name: "道袍·精", lvl: 4, price: 12000 },
        { id: 106, name: "礼服·精", lvl: 5, price: 24000 },
        { id: 107, name: "蚕服·精", lvl: 6, price: 48000 },
        { id: 108, name: "庙服·精", lvl: 7, price: 96000 },
        { id: 109, name: "朝服·精", lvl: 8, price: 192000 },
        { id: 110, name: "长冠服·精", lvl: 9, price: 384000 },
        { id: 111, name: "冕冠服·精", lvl: 10, price: 768000 }
    ],
    // base=4: 衣类防具（速）
    4: [
        { id: 112, name: "单衣·速", lvl: 1, price: 1500 },
        { id: 113, name: "短衣·速", lvl: 2, price: 3000 },
        { id: 114, name: "长袍·速", lvl: 3, price: 6000 },
        { id: 115, name: "道袍·速", lvl: 4, price: 12000 },
        { id: 116, name: "礼服·速", lvl: 5, price: 24000 },
        { id: 117, name: "蚕服·速", lvl: 6, price: 48000 },
        { id: 118, name: "庙服·速", lvl: 7, price: 96000 },
        { id: 119, name: "朝服·速", lvl: 8, price: 192000 },
        { id: 120, name: "长冠服·速", lvl: 9, price: 384000 },
        { id: 121, name: "冕冠服·速", lvl: 10, price: 768000 }
    ],
    // base=5: 铠类防具（均）
    5: [
        { id: 122, name: "皮铠·均", lvl: 1, price: 1500 },
        { id: 123, name: "青铜铠·均", lvl: 2, price: 3000 },
        { id: 124, name: "镔铁铠·均", lvl: 3, price: 6000 },
        { id: 125, name: "精钢铠·均", lvl: 4, price: 12000 },
        { id: 126, name: "乌金铠·均", lvl: 5, price: 24000 },
        { id: 127, name: "混元铠·均", lvl: 6, price: 48000 },
        { id: 128, name: "地煞铠·均", lvl: 7, price: 96000 },
        { id: 129, name: "天罡铠·均", lvl: 8, price: 192000 },
        { id: 130, name: "亮银铠·均", lvl: 9, price: 384000 },
        { id: 131, name: "紫金铠·均", lvl: 10, price: 768000 }
    ]
};

class ArmorBaseUpdater {
    constructor() {
        this.connection = null;
        this.dbConfig = dbConfig;
    }

    // 建立数据库连接
    async connect() {
        try {
            this.connection = await mysql.createConnection(this.dbConfig);
            console.log('✅ 数据库连接成功');
        } catch (error) {
            console.error('❌ 数据库连接失败:', error.message);
            throw error;
        }
    }

    // 关闭数据库连接
    async disconnect() {
        if (this.connection) {
            await this.connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }

    // 检查equipment_base表是否存在
    async checkTableExists() {
        try {
            console.log('🔍 检查equipment_base表是否存在...');
            
            const [rows] = await this.connection.execute(`
                SELECT COUNT(*) as count 
                FROM information_schema.tables 
                WHERE table_schema = '${this.dbConfig.database}' 
                AND table_name = 'equipment_base'
            `);

            const exists = rows[0].count > 0;
            console.log(`📊 equipment_base表${exists ? '存在' : '不存在'}`);
            return exists;
        } catch (error) {
            console.error('❌ 检查表存在性失败:', error.message);
            throw error;
        }
    }

    // 获取当前防具数据
    async getCurrentArmorData() {
        try {
            console.log('📋 获取当前防具数据...');
            
            const [rows] = await this.connection.execute(`
                SELECT id, name, base, level, price, type
                FROM equipment_base 
                WHERE type = 3
                ORDER BY id
            `);

            console.log(`📊 当前表中有 ${rows.length} 条防具数据`);
            return rows;
        } catch (error) {
            console.error('❌ 获取当前防具数据失败:', error.message);
            throw error;
        }
    }

    // 更新防具的base值
    async updateArmorBase(baseValue, armorList) {
        try {
            console.log(`🔄 开始更新防具base=${baseValue}的数据...`);
            
            let successCount = 0;
            let errorCount = 0;

            for (const armor of armorList) {
                try {
                    const updateSQL = `
                        UPDATE equipment_base 
                        SET base = ?, level = ?, price = ? 
                        WHERE id = ? AND name = ? AND type = 3
                    `;

                    const [result] = await this.connection.execute(updateSQL, [
                        baseValue,
                        armor.lvl,
                        armor.price.toString(),
                        armor.id,
                        armor.name
                    ]);

                    if (result.affectedRows > 0) {
                        successCount++;
                        console.log(`✅ 更新防具: ${armor.name} (ID: ${armor.id}) -> base=${baseValue}, lvl=${armor.lvl}, price=${armor.price}`);
                    } else {
                        errorCount++;
                        console.log(`⚠️ 未找到防具: ${armor.name} (ID: ${armor.id})`);
                    }
                } catch (error) {
                    errorCount++;
                    console.error(`❌ 更新防具失败 (ID: ${armor.id}):`, error.message);
                }
            }

            console.log(`📊 base=${baseValue} 更新完成: 成功 ${successCount} 条, 失败 ${errorCount} 条`);
            return { successCount, errorCount };
        } catch (error) {
            console.error(`❌ 更新base=${baseValue}防具失败:`, error.message);
            throw error;
        }
    }

    // 验证更新结果
    async verifyUpdate() {
        try {
            console.log('🔍 验证防具更新结果...');

            // 按base值分组统计防具
            const [rows] = await this.connection.execute(`
                SELECT base, COUNT(*) as count, 
                       MIN(level) as min_level, MAX(level) as max_level,
                       MIN(CAST(price AS UNSIGNED)) as min_price, MAX(CAST(price AS UNSIGNED)) as max_price
                FROM equipment_base 
                WHERE type = 3 AND base IN (1, 2, 3, 4, 5)
                GROUP BY base 
                ORDER BY base
            `);

            console.log('📋 按base值分组的防具统计:');
            rows.forEach(row => {
                console.log(`   base=${row.base}: ${row.count}个防具, 等级${row.min_level}-${row.max_level}, 价格${row.min_price}-${row.max_price}`);
            });

            // 显示每个base的前3个防具作为示例
            for (let base = 1; base <= 5; base++) {
                const [sampleRows] = await this.connection.execute(`
                    SELECT id, name, base, level, price 
                    FROM equipment_base 
                    WHERE type = 3 AND base = ? 
                    ORDER BY level 
                    LIMIT 3
                `, [base]);

                console.log(`📋 base=${base} 前3个防具示例:`);
                sampleRows.forEach(row => {
                    console.log(`   ID: ${row.id}, 名称: ${row.name}, 等级: ${row.level}, 价格: ${row.price}`);
                });
            }

        } catch (error) {
            console.error('❌ 验证防具更新结果失败:', error.message);
            throw error;
        }
    }

    // 运行完整的更新流程
    async runUpdate() {
        console.log('🚀 开始更新防具装备base值...\n');

        try {
            // 1. 连接数据库
            await this.connect();

            // 2. 检查表是否存在
            const tableExists = await this.checkTableExists();
            if (!tableExists) {
                throw new Error('equipment_base表不存在');
            }

            // 3. 获取当前防具数据
            await this.getCurrentArmorData();

            // 4. 更新各个base值的防具
            let totalSuccess = 0;
            let totalError = 0;

            for (const [baseValue, armorList] of Object.entries(armorData)) {
                const result = await this.updateArmorBase(parseInt(baseValue), armorList);
                totalSuccess += result.successCount;
                totalError += result.errorCount;
                console.log(''); // 空行分隔
            }

            // 5. 验证更新结果
            await this.verifyUpdate();

            console.log('\n📊 防具更新完成统计:');
            console.log(`   总成功: ${totalSuccess} 条`);
            console.log(`   总失败: ${totalError} 条`);
            console.log(`   总计: ${totalSuccess + totalError} 条`);

            console.log('\n🎉 防具装备base值更新完成！');

        } catch (error) {
            console.error('\n💥 更新过程中发生错误:', error.message);
            throw error;
        } finally {
            // 6. 关闭连接
            await this.disconnect();
        }
    }
}

// 运行更新
async function main() {
    console.log('🎯 防具装备base值更新脚本');
    console.log('   功能：根据防具数据更新equipment_base表中对应防具的base值\n');

    const updater = new ArmorBaseUpdater();
    await updater.runUpdate();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 更新脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = ArmorBaseUpdater;
